<template>
  <div class="tourist-track-wrapper">
    <v-header title="路线规划"></v-header>
    <div :style="{height: mainHeight + 'px'}" style="overflow-y: scroll;">
      <div class="product" v-lazy:backgroundImage="product.thumbUrl">
      </div>
      <div class="info">
        <p class="product-title">{{product.name}}</p>
        <p class="product-feature">{{product.feature}}</p>
      </div>

      <ul class="track" v-if="product.track">
        <li v-for="(item, index) in product.track" :key="index">
          <p class="start">
            <i class="icon iconfont icon-point" :style="{color: colors[index]}"></i>
            <span class="index">{{index + 1}}</span>
            <span class="title">{{item.start}}</span>
            <span class="remark" v-if="item.remark">({{item.remark}})</span>
            <img />
          </p>
          <ul class="ways" v-if="item.ways && item.ways.length > 0" ref="ways" :style="{height: 45 + 'px'}">
            <li v-for="(way, index1) in item.ways" :key="index1">
              <span class="way-type"><i class="icon iconfont" :class="'icon-' + way.icon" :style="{color: colors[index]}"></i>{{way.typeName}}</span>
              <span class="way-price"><span class="label">费用:</span>{{way.price}}元</span>
              <span class="way-time"><span class="label">时间:</span>{{way.duration}}</span>
              <i v-if="item.ways.length > 1 && index1 === 0 && !item.open" @click.stop="toggleExpond(index)" class="expond icon iconfont icon-down"></i>
              <i v-if="item.ways.length > 1 && index1 === item.ways.length - 1 && item.open" @click.stop="toggleExpond(index)" class="expond icon iconfont icon-up"></i>
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import VHeader from '@/components/v-header/v-header'

import { isIphoneX } from '@/assets/js/brower'
import { mapMutations } from 'vuex'
import { getDistance } from '@/assets/js/amap'
import nativeBridge from '@/assets/js/nativeBridge'

// 西江千户苗寨的路线
// type  0 步行  1 公交  2 滴滴  3 神舟专车  4 火车  5 高铁  6 飞机  7 直达车
const XIJIANG_TRACK = [
  {
    start: '太升国际',
    end: '贵阳北站',
    remark: '我的位置',
    open: false,
    ways: [
      {
        type: 1,
        icon: 'bus',
        typeName: '公交车',
        distance: '24.8Km',
        duration: '42分钟',
        price: '2'
      },
      {
        type: 2,
        icon: 'car',
        typeName: '滴滴',
        distance: '21.1Km',
        duration: '35分钟',
        price: '40'
      },
      {
        type: 3,
        icon: 'car',
        typeName: '神舟专车',
        distance: '21.1Km',
        duration: '33分钟',
        price: '85'
      }
    ]
  },
  {
    start: '贵阳北站',
    typeName: '高铁',
    end: '凯里南站',
    open: false,
    ways: [
      {
        type: 5,
        icon: 'train',
        typeName: '高铁/动车',
        distance: '167Km',
        duration: '38分钟',
        price: '58.5'
      }
    ]
  },
  {
    start: '凯里南站',
    end: '西江千户苗寨',
    open: false,
    ways: [
      {
        type: 7,
        icon: 'bus',
        typeName: '直达车',
        distance: '42.5Km',
        duration: '32分钟',
        price: '25'
      }
    ]
  },
  {
    start: '西江千户苗寨',
    remark: '目的地',
    open: false
  }
]
const ZHAOXING_TRACK = [
  {
    start: '太升国际',
    end: '贵阳北站',
    remark: '我的位置',
    open: false,
    ways: [
      {
        type: 1,
        icon: 'bus',
        typeName: '公交车',
        distance: '24.8Km',
        duration: '42分钟',
        price: '2'
      },
      {
        type: 2,
        icon: 'car',
        typeName: '滴滴',
        distance: '21.1Km',
        duration: '35分钟',
        price: '40'
      },
      {
        type: 3,
        icon: 'car',
        typeName: '神舟专车',
        distance: '21.1Km',
        duration: '33分钟',
        price: '85'
      }
    ]
  },
  {
    start: '贵阳北站',
    end: '凯里南站',
    ways: [
      {
        type: 5,
        typeName: '高铁/动车',
        distance: '167Km',
        duration: '38分钟',
        price: '58.5'
      }
    ]
  },
  {
    start: '凯里南站',
    end: '西江千户苗寨',
    ways: [
      {
        type: 7,
        typeName: '直达车',
        distance: '42.5Km',
        duration: '32分钟',
        price: '25'
      }
    ]
  },
  {
    start: '西江千户苗寨',
    remark: '目的地'
  }
]

const productList = [
  {
    id: '0',
    productId: '',
    name: '西江千户苗寨',
    thumbUrl: 'http://qiniucdn.iwiteks.com/152645983861627758dae-7aa1-4545-9184-a176cf59d924.png',
    feature: '西江千户苗寨是一个保存苗族“原始生态”文化完整的地方，由10余个依山而建的自然村寨相连成片，是目前中国乃至全世界最大的苗族聚居村寨。它是领略和认识中国苗族漫长历史与发展之地.',
    track: XIJIANG_TRACK
  },
  {
    id: '1',
    productId: '',
    name: '肇兴侗寨',
    thumbUrl: 'http://qiniucdn.iwiteks.com/15264598982626f1e3db3-0b8e-4fdf-9b8e-e8cc47abe2f7.png',
    feature: '肇兴侗寨，位于贵州省黔东南苗族侗族自治州黎平县东南部，占地18万平方米，居民1000余户，6000多人，是全国最大的侗族村寨之一，素有"侗乡第一寨"之美誉。',
    track: ZHAOXING_TRACK
  }
]

const GUIYANGBEI = [106.674349, 26.619625]

export default {
  data () {
    return {
      colors: ['#ff9e05', '#6ac302', '#00ceb9', '#25a1f8', '#907ffe', '#dc60fa', '#ff6946'],
      product: null
    }
  },
  components: {
    VHeader
  },
  computed: {
    // ...mapGetters(['position'])
  },
  created () {
    this.mainHeight = window.innerHeight - 40 - 24
    if (isIphoneX()) {
      this.mainHeight = window.innerHeight - 40 - 34
    }
    this.product = productList.find(o => o.id === this.$route.params.id)

    const _self = this
    nativeBridge.getPosition(this, (arg, geo) => {
      const position = [parseFloat(arg.longitude), parseFloat(arg.latitude)]
      _self.setPosition(position)
      const track = {
        start: geo.aoiName,
        end: '贵阳北站',
        remark: '我的位置',
        open: false,
        ways: []
      }
      const distance = getDistance(position, GUIYANGBEI)
      let walkWay = null
      let transferWay = null
      let carWay = _self.carWay(position, GUIYANGBEI)
      if (distance < 1200) {
        // 距离小于2Km时，步行
        walkWay = _self.walkWay(position, GUIYANGBEI)
      } else if (distance < 3000) {
        // 距离小于3Km时，步行、 公交
        walkWay = _self.walkWay(position, GUIYANGBEI)
        transferWay = _self.transferWay(position, GUIYANGBEI)
      } else if (distance < 32000) {
        // 距离小于32Km时，公交
        transferWay = _self.transferWay(position, GUIYANGBEI)
      }
      Promise.all([walkWay, transferWay, carWay]).then((data) => {
        // data.length 和 出行方式 对应
        /*
          {
            type: 2,
            icon: 'car',
            typeName: '滴滴',
            distance: '21.1Km',
            duration: '35分钟',
            price: '40'
          },
          {
            type: 3,
            icon: 'car',
            typeName: '神舟专车',
            distance: '21.1Km',
            duration: '33分钟',
            price: '85'
          }
        */
        const walk = data[0]
        if (walk && walk.routes && walk.routes.length > 0) {
          const route = walk.routes[0]
          track.ways.push({
            type: 0,
            icon: 'walk',
            typeName: '步行',
            distance: (route.distance / 1000).toFixed(1) + 'Km',
            duration: _self.formatTime(route.time),
            price: 0
          })
        }
        const trans = data[1]
        if (trans && trans.plans && trans.plans.length > 0) {
          const plan = trans.plans[0]
          track.ways.push({
            type: 1,
            icon: 'bus',
            typeName: '公交车',
            distance: (plan.distance / 1000).toFixed(1) + 'Km',
            duration: _self.formatTime(plan.time),
            price: plan.cost
          })
        }
        const car = data[2]
        if (car && car.routes && car.routes.length > 0) {
          const route = car.routes[0]
          const distance = (route.distance / 1000).toFixed(1)
          const didiPrice = distance <= 3 ? 10 : 10 + (distance - 3) * 2.8
          const shenzhouPrice = distance <= 3 ? 14 : 14 + (distance - 3) * 3.1
          track.ways.push({
            type: 2,
            icon: 'car',
            typeName: '滴滴',
            distance: distance + 'Km',
            duration: _self.formatTime(route.time),
            price: didiPrice.toFixed(1)
          })
          track.ways.push({
            type: 3,
            icon: 'car',
            typeName: '神舟专车',
            distance: distance + 'Km',
            duration: _self.formatTime(route.time * 0.9),
            price: shenzhouPrice.toFixed(1)
          })
        }
        _self.product.track.splice(0, 1, track)
      })
    })
  },
  methods: {
    toggleExpond (index) {
      this.product.track[index].open = !this.product.track[index].open
      this.$refs.ways[index].style.height = this.product.track[index].open ? this.product.track[index].ways.length * 45 + 'px' : '45px'
    },
    transferWay (start, end) {
      // 公交
      return new Promise((resolve, reject) => {
        AMap.service(['AMap.Transfer'], function() {
          var transOptions = {
            city: '贵阳市',
            policy: AMap.TransferPolicy.LEAST_TIME
          }
          var trans = new AMap.Transfer(transOptions)
          trans.search(start, end, function(status, result) {
            if (status === 'complete') {
              resolve(result)
            } else {
              reject()
            }
          })
        })
      })
    },
    walkWay (start, end) {
      // 步行
      return new Promise((resolve, reject) => {
        AMap.service(['AMap.Walking'], function() {
          var walk = new AMap.Walking()
          walk.search(start, end, function(status, result) {
            if (status === 'complete') {
              resolve(result)
            } else {
              reject()
            }
          })
        })
      })
    },
    carWay (start, end) {
      // 开车
      return new Promise((resolve, reject) => {
        AMap.service(['AMap.Driving'], function() {
          var walk = new AMap.Driving()
          walk.search(start, end, function(status, result) {
            if (status === 'complete') {
              resolve(result)
            } else {
              reject()
            }
          })
        })
      })
    },
    formatTime (time) {
      const minute = Math.floor(time / 60)
      if (minute < 60) {
        return minute + '分钟'
      }
      const hour = Math.floor(minute / 60)
      return hour + '小时' + (minute % 60) + '分'
    },
    ...mapMutations({
      setPosition: 'SET_POSITION'
    })
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/css/variable.styl'
@import '~@/assets/css/mixins.styl'

.tourist-track-wrapper
  position fixed
  top 0
  left 0
  right 0
  bottom 0
  z-index 101
  background #ffffff
  .product
    height 180px
    position relative
    background-size cover
    background-repeat no-repeat
    background-position 50% 50%
  .info
    padding 20px 16px
    .product-title
      display inline-block
      font-size 20px
      color #333
      font-weight bold
      line-height 1
      margin-bottom 16px
    .product-feature
      font-size 12px
      color #999
      line-height 18px
.track
  position relative
  padding-left 40px
  margin-bottom 40px
  &:before
    content ''
    display block
    position absolute
    width 5px
    height 100%
    left 20px
    top 0
    background-image url(./track_point.png)
    background-repeat repeat
    background-size 100% auto
  .start
    height 44px
    line-height 44px
    padding-right 16px
    position relative
    .title
      color #333
      font-size 15px
      font-weight bold
    .remark
      font-size 13px
      color #999
      font-weight normal
      margin-left 8px
    i
      position absolute
      left -28px
      top 0px
      font-size 21px
    .index
      position absolute
      left -21.5px
      top -2px
      color #fff
      font-size 12px
.ways
  transition height .4s
  background #fff
  overflow hidden
  li
    height 44px
    line-height 44px
    color #333
    font-size 13px
    display flex
    border-bottom 0.5px solid $color-border
    position relative
  .label
    color #999
  .way-type
    width 90px
    display inline-block
    i
      margin-right 6px
  .way-price
    width 88px
    display inline-block
  .expond
    position absolute
    right 16px
    top 2px
    font-size 16px
    color #999
</style>
